<?php

/**
 * login actions.
 *
 * @package    RetailBrain
 * @subpackage login
 * @author     Álvaro Peña Cataldo
 */
class loginActions extends sfActions {


    /**
     * Executes index action
     *
     * @param sfRequest $request A request object
     */
    public function executeIndex(sfWebRequest $request) {
        $this->setLayout('login');
    }

    public function executeLogout() {
        if ($this->getUser()->isAuthenticated()) {
            $this->getUser()->setAuthenticated(false);
            $this->getUser()->getAttributeHolder()->clear();
            $this->setLayout('login');
            $this->forward('login', 'index');
        }else{
            $this->setLayout('login');
            $this->forward('login', 'index');
        }
    }

    public function executeAcceso() {
        $usuario = $this->getUsuario();

        $params = array();

        if (myCapability::testcap($usuario->caps, myCapability::C('CAP_LOGIN'))) {
            if (($usuario instanceof USERS) && isset($usuario->id_users)) {
                $this->getUser()->setAuthenticated(true);

                $this->msg = "";
                $this->getUser()->setUser($usuario);
                $this->getUser()->setAttribute("username", $usuario->username);
                $this->getUser()->setAttribute("id_users", $usuario->id_users);
                $this->getUser()->setAttribute("caps", $usuario->caps);
                $this->getUser()->setAttribute("nombre", $usuario->name . " " . $usuario->last_name);

                /**
                 * TODO: Redireccionar de acuerdo al perfil 
                 */
                //$this->forward('home', 'index');
                $this->redirect('home/index');
            }
            
        }else{
            $this->forward('login', 'index');
        }
        
        return sfView::NONE;
    }

    private function getUsuario() {

        $_obj = Doctrine_Query::create()
                        ->from("Users u")
                        ->where("lower(u.username) = ? and u.password= ? ",
                                array(strtolower($this->getRequestParameter("username")),
                                    md5($this->getRequestParameter("password")))
        );
        return $_obj->fetchOne();
    }
    
    
    

}
